package com.copa.gamestore.security.service;

import com.copa.gamestore.module.user.application.UserApplicationService;
import com.copa.gamestore.module.user.domain.User;
import com.copa.gamestore.security.domain.AuthenticUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author copa
 * @createDate 2022-09-22 11:25
 * @function 认证用户信息查询服务
 */
@Component
public class AuthenticUserDetailsService implements UserDetailsService {

    @Resource
    private UserApplicationService userApplicationService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = Optional.ofNullable(userApplicationService.findByUsername(username)).orElseThrow(() -> new UsernameNotFoundException("用户" + username + "不存在"));
        List<String> roleNameList = userApplicationService.roleNameByUserId(user.getId());
        if (Objects.isNull(roleNameList) || roleNameList.isEmpty()) {
            throw new UsernameNotFoundException("用户" + username + "没有权限");
        }
        return new AuthenticUser(user, roleNameList);
    }
}
